package com.dji.custom.util;

import cn.hutool.core.lang.UUID;
import org.dom4j.Element;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CustomUtil {

    public static String substringAfterLast(String str, String separator) {
        if (isEmpty(str)) {
            return str;
        } else if (isEmpty(separator)) {
            return "";
        } else {
            int pos = str.lastIndexOf(separator);
            return pos != -1 && pos != str.length() - separator.length() ? str.substring(pos + separator.length()) : "";
        }
    }
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static String fastSimpleUUID()
    {
        return UUID.fastUUID().toString(true);
    }

    public static File urlToFile(URL url) {
        InputStream is = null;
        File file = null;
        FileOutputStream fos = null;
        try {
            file = File.createTempFile("tmp", null);
            URLConnection urlConn = null;
            urlConn = url.openConnection();
            is = urlConn.getInputStream();
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = is.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }
            return file;
        } catch (IOException e) {
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }
    public static void listNodes(Element node, List<Map> nodeList) {
        //System.out.println("当前结点的名称:" + node.getName() + "当前节点的值" + node.getTextTrim());
        if ("coordinates".equals(node.getName())) {
            String s = node.getTextTrim();
            String[] str = s.split(",");
            Double d0 = new Double(str[0]);//经度
            Double d1 = new Double(str[1]);//纬度
            Map map = new HashMap();
            map.put("index",nodeList.size()+1);
            map.put("lng",d0);
            map.put("lat",d1);
            nodeList.add(map);
            //System.out.println("经度:" + d0 + "纬度" + d1);
        }
        //同一时候迭代当前节点以下的全部子节点
        //使用递归
        Iterator<Element> iterator = node.elementIterator();
        while (iterator.hasNext()) {
            Element e = iterator.next();
            listNodes(e, nodeList);
        }
    }

}
